'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/authorizedj/kh/add 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			xcxinfo
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------



		console.log("xcxinfo", xcxinfo);

		let A = await vk.baseDao.selects({
			dbName: "a_appid",
			// 主表where条件
			whereJson: {
				appid: xcxinfo.ma_app_id
			},
		});

		console.log("A========", A);


		let appsecret = A.rows[0].appsecret

		const app_id_list = xcxinfo.app_id_list

		// 将字符串转换为数组
		// const appIdArray = app_id_list.split(';');

		// 将数组转换为列表
		const appIdList = app_id_list.map(appId => appId);

		console.log(appIdList);


		let urlA = "https://open.douyin.com/oauth/client_token/"
		const accessToken = await uniCloud.httpclient.request(urlA, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
			},
			data: {
				client_key: xcxinfo.ma_app_id, // id
				client_secret: appsecret, // 密钥
				grant_type: "client_credential",
			},
			dataType: 'json', // 指定返回值为json格式，自动进行parseK
		})

		//创建短剧
		// 有效时间为 2 个小时
		let access_token = accessToken.data.data.access_token

		let urlT = "https://open.douyin.com/api/playlet/v2/auth/authorize/"
		const responseText = await uniCloud.httpclient.request(urlT, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
				"access-token": access_token,
			},
			data: {
				ma_app_id: xcxinfo.ma_app_id,
				album_id: xcxinfo.album_id,
				app_id_list: appIdList,
			},
			dataType: 'json', // 指定返回值为json格式，自动进行parseK
		})
		console.log("responseText", responseText);
		if (responseText.data.err_msg) {
			return {
				code: 1,
				msg: "请先完成页面绑定参数不合法"
			};

		}
		// 添加至数据库
		let num = await vk.baseDao.add({
			dbName: "dy_authorizedj", // 表名
			dataJson: { // 需要新增的数据 json格式
				ma_app_id: xcxinfo.ma_app_id,
				album_id: xcxinfo.album_id,
				app_id_list: appIdList,
				title: xcxinfo.title
			}
		});


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}